# -*- coding: utf-8 -*-
"""
@Author: thekernel
@Date: 2020/6/21 16:11
@Description: 商大云战役 自动提交
@Environment: ubuntu64
@Explanation: 设置定时
    vim /etc/crontab
    加入: 3 0 * * * /root/zjgsu/run.sh (minute hour week month year shell)
    service cron restart
"""
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

import time
import random

import requests
import datetime

import smtplib
from email.mime.text import MIMEText
from email.header import Header

USERNAME = "1711090325"
PASSWORD = "212219"
DRIVER_PATH = "/root/zjgsu/chromedriver"
RECEIVE_EMAIL = "837853431@qq.com"


def login(browser):
    username_input = browser.find_element_by_id("name")
    password_input = browser.find_element_by_id("psswd")
    commit_button = browser.find_element_by_id("login-btn")

    username_input.send_keys(USERNAME)
    password_input.send_keys(PASSWORD)
    commit_button.click()

    time.sleep(3 + random.random())

    commit(chrome)


def commit(browser):
    commit = browser.find_element_by_class_name("ui-btn")
    commit.click()
    time.sleep(3 + random.random())

    if "成功" in browser.page_source:
        requests.post(url="http://api.kernelylz.cn:8008/api/v1/email/sendVerifyEmail",
                      json={"toEmail": RECEIVE_EMAIL})
        with open("/root/zjgsu/date.log", "a", encoding="utf-8") as f:
            f.writelines(str(datetime.datetime.now().year) + "/")
            f.writelines(str(datetime.datetime.now().month) + "/")
            f.writelines(str(datetime.datetime.now().day) + "\t")
            f.writelines("success" + "\n")
    else:
        with open("/root/zjgsu/date.log", "a", encoding="utf-8") as f:
            f.writelines(str(datetime.datetime.now().year) + "/")
            f.writelines(str(datetime.datetime.now().month) + "/")
            f.writelines(str(datetime.datetime.now().day) + "\t")
            f.writelines("fail" + "\n")


# TODO: 成功则发送邮件
def send_success_email():
    smtp = smtplib.SMTP_SSL("smtp.163.com", 994)
    sender = "thekernelz@163.com"
    smtp.login(user=sender, password="Kernel990621")

    message = MIMEText('商大云战役签到成功', 'plain', 'utf-8')
    message['From'] = Header("thekernel", 'utf-8')  # 发送者
    message['To'] = Header("thekernel", 'utf-8')  # 接收者

    subject = '云战役签到成功'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtp.sendmail(sender, RECEIVE_EMAIL, message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")


if __name__ == '__main__':
    url = "https://nco.zjgsu.edu.cn/login"

    options = webdriver.ChromeOptions()
    mobile_emulation = {"deviceName": "Galaxy S5"}
    options.headless = True
    capabilities = DesiredCapabilities.CHROME
    capabilities['loggingPrefs'] = {'browser': 'ALL'}
    options.add_experimental_option("mobileEmulation", mobile_emulation)
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-gpu')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument(
        "user-agent=" + "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like "
                        "Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1")
    chrome = webdriver.Chrome(desired_capabilities=capabilities, options=options, executable_path=DRIVER_PATH)

    chrome.get(url)
    login(chrome)
